﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI;
using System.Reflection;
using Elkitools.EditorParts.ListSelector.Controls;
using Elkitools.EditorParts.ListSelector.Tools;


namespace Elkitools.EditorParts.ListSelector.EditorParts
{
    /// <summary>
    /// This class provides help to select any Event SPList in the current SPSite 
    /// </summary>
    public class CalendarWebsAndListsEditorPart : EditorPart
    {
        /// <summary>
        /// UserControl that displays all the hierarchy
        /// </summary>
        internal CalendarsWebsAndLists CalendarsHierarchy { get; set; }

        /// <summary>
        /// This is the Property to be Read or Written by the editor
        /// </summary>
        internal PropertyInfo WebPartPropertyToManage { get; set; }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            // Add the CalendarWebsAndLists Control
            CalendarsHierarchy = new CalendarsWebsAndLists();
            this.Controls.Add(CalendarsHierarchy);
        }

        /// <summary>
        /// Set WebPart properties
        /// </summary>
        /// <returns></returns>
        public override bool ApplyChanges()
        {
            bool result = false;

            EnsureChildControls();
            DemoWebPart wp = this.WebPartToEdit as DemoWebPart;

            try
            {
                WebPartPropertyToManage.SetValue(wp, CalendarsHierarchy.ListsUrls, null);
                //wp.SitesUrl = CalendarsHierarchy.ListsUrls;
                result = true;

                //UlsLogger.Debug("[ApplyChanges (" + WebPartPropertyToManage.Name + ")] EditorPart.ListsUrls = " + CalendarsHierarchy.ListsUrls);
            }
            catch (Exception excSetWPListsUrl)
            {
                UlsLogger.Error("An error occurred while defining the WebParts's 'WebPartPropertyToManage' property : " + excSetWPListsUrl.Message);
                result = false;
            }

            return result;
        }

        /// <summary>
        /// Get WebPart Properties
        /// </summary>
        public override void SyncChanges()
        {
            EnsureChildControls();
            DemoWebPart wp = this.WebPartToEdit as DemoWebPart;

            try
            {
                CalendarsHierarchy.ListsUrls = ("" + WebPartPropertyToManage.GetValue(wp, null)).ToString();

                //UlsLogger.Debug("[SyncChanges (" + WebPartPropertyToManage.Name + ")] EditorPart.ListsUrls = " + CalendarsHierarchy.ListsUrls);
            }
            catch (Exception excSetListsUrls)
            {
                UlsLogger.Error("An error occurred while defining the Editor's 'WebPartPropertyToManage' property : " + excSetListsUrls.Message);
            }
        }
    }
}
